//
//  CoreDataUtils.m
//  iShop
//
//  Created by svp on 1/6/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "CoreDataUtils.h"
#import "Utils.h"
#import "ConstansDefine.h"
#import "WishList.h"

@implementation CoreDataUtils

+(NSManagedObject*) getObjectEntity:(NSString*)entity fromCondition:(NSDictionary*)condition;
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entityDesc = [NSEntityDescription    
									   entityForName:entity inManagedObjectContext:context];
	
	
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	
	[request setEntity:entityDesc];
	NSMutableArray *preds = [[NSMutableArray alloc] init];
	NSArray *keys = [condition allKeys];
	for (NSString *field in keys) {
		[preds addObject:[NSPredicate predicateWithFormat:@"%K == %@",field,[condition objectForKey:field]]];
	}
		
	[request setPredicate:[NSCompoundPredicate andPredicateWithSubpredicates:preds]];
	
	NSError *error;
	
	NSArray *matching_objects = [context executeFetchRequest:request error:&error]; 
	if (matching_objects != nil && matching_objects.count > 0) {
		return [matching_objects lastObject];
	}
	return nil;
}

+(void) updateCategory:(NSArray*)subCategoryObjs
{
	for (Category *subCategory in subCategoryObjs) {
		NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
		NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Category" inManagedObjectContext:context];
		NSFetchRequest *request = [[NSFetchRequest alloc] init];
		[request setEntity:entity];
		NSPredicate *predicate = [NSPredicate predicateWithFormat:@"CategoryID == %@",subCategory.ParentCategoryID];
		[request setPredicate:predicate];
		NSError *error;
		NSArray *objects = [context executeFetchRequest:request error:&error];
		if (objects != nil && objects.count > 0) {
			for (Category *parentCategory in objects) {
				subCategory.ParentCategory = parentCategory;
			}
		}
		else {
			if (error != NULL) {
				NSLog(@"error:%@",[error description]);
			}			
		}

	}
}

+(NSArray*) getRootCategoryFromShop:(Shop*)shop
{
	NSArray *productsShop = [CoreDataUtils getProductsFromShop:shop];
	NSMutableArray *rs = [[[NSMutableArray alloc] init] autorelease];
	for (Product *p in productsShop) {
		if (p.BaseProduct.Category.ParentCategory && ![rs containsObject:p.BaseProduct.Category.ParentCategory]) {
			[rs addObject:p.BaseProduct.Category.ParentCategory];
		}
	}
	NSSortDescriptor *sortDescriptor;
	
	NSString *sortKey = @"";
	
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		sortKey = @"CategoryOrder";
	}
	else {
		sortKey = @"CustomerCategoryOrder";
	}
	
	sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:sortKey
												  ascending:YES] autorelease];
	NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
	
	return [rs sortedArrayUsingDescriptors:sortDescriptors];		 
}

+(NSArray*) getSubCategoryFromShop:(Shop*)shop rootCategory:(Category*)category
{
	NSArray *productsShop = [CoreDataUtils getProductOnShop:shop andCategory:category];
	NSMutableArray *rs = [[[NSMutableArray alloc] init] autorelease];
	for (Product *p in productsShop) {
		if (p.BaseProduct.Category && ![rs containsObject:p.BaseProduct.Category]) {
			[rs addObject:p.BaseProduct.Category];
		}
	}
	NSSortDescriptor *sortDescriptor;
	
	NSString *sortKey = @"";
	
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		sortKey = @"CategoryOrder";
	}
	else {
		sortKey = @"CustomerCategoryOrder";
	}
	
	sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:sortKey
												  ascending:YES] autorelease];
	NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
	
	return [rs sortedArrayUsingDescriptors:sortDescriptors];		 
}

+(NSArray*) getProductOnShop:(Shop*)shop andCategory:(Category*)category
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Product" inManagedObjectContext:context];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:entity];
	NSPredicate *predicate;
	if (category.ParentCategory) 
	{
		predicate = [NSPredicate predicateWithFormat:@"Shop == %@ && BaseProduct.Category == %@",shop,category];
	}
	else 
	{
		predicate = [NSPredicate predicateWithFormat:@"Shop == %@ && BaseProduct.Category.ParentCategory == %@",shop,category];
	}	
	[request setPredicate:predicate];
	
	[request setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"ProductUnitPrice" ascending:YES]]];
	
	
	NSError *error;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects == nil) {
		abort();
	}

	if (objects && objects.count > 0) {
		NSMutableArray *cArr= [NSMutableArray arrayWithArray:objects];
		for (int i=0; i<cArr.count; i++) {
			for (int j=i+1;j<objects.count; j++) {
				Product *objA = (Product*)[cArr objectAtIndex:i];
				Product *objB = (Product*)[cArr objectAtIndex:j];
				if ([objA.BaseProduct.Brand.BrandCheck intValue] < [objB.BaseProduct.Brand.BrandCheck intValue]) {
					[cArr exchangeObjectAtIndex:i withObjectAtIndex:j]; 
				}
				else if([objA.BaseProduct.Brand.BrandCheck intValue] == [objB.BaseProduct.Brand.BrandCheck intValue] &&[objA.BaseProduct.Brand.BrandName compare:objB.BaseProduct.Brand.BrandName] == NSOrderedDescending)
				{
					[cArr exchangeObjectAtIndex:i withObjectAtIndex:j]; 
				}
				else if([objA.BaseProduct.Brand.BrandCheck intValue] == [objB.BaseProduct.Brand.BrandCheck intValue] &&[objA.BaseProduct.Brand.BrandName compare:objB.BaseProduct.Brand.BrandName] == NSOrderedDescending && [objA.ProductUnitPrice compare:objB.ProductUnitPrice] == NSOrderedDescending)
				{
					[cArr exchangeObjectAtIndex:i withObjectAtIndex:j];
				}
			}
		}
		return cArr;
	}
	return objects;
}

+(NSUInteger) countProductOnShop:(Shop*)shop andCategory:(Category*)category
{	
	return [CoreDataUtils getProductOnShop:shop andCategory:category].count;
}

+(NSArray*) getProductsFromShop:(Shop*)shop
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Product" inManagedObjectContext:context];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:entity];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Shop == %@",shop];
	[request setPredicate:predicate];
	NSError *error;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects == nil) {
		abort();
	}
	return objects;
}

+(NSArray*) getMainCategory
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Category" inManagedObjectContext:context];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:entity];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ParentCategory == %@",[NSNull null]];
	[request setPredicate:predicate];
	
	NSString *sortKey = @"";
	
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		sortKey = @"CategoryOrder";
	}
	else {
		sortKey = @"CustomerCategoryOrder";
	}
	
	
	
	[request setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:sortKey ascending:YES]]];
	
	
	NSError *error;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects != nil && objects.count > 0) {
		return objects;
	}
	else {
		if (error != nil) {
			NSLog(@"error:%@",[error description]);
		}			
	}
	return nil;
}

+(NSArray*) getSubCategory:(Category*)category
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Category" inManagedObjectContext:context];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:entity];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ParentCategory == %@",category];
	[request setPredicate:predicate];
	
	NSString *sortKey = @"";
	
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		sortKey = @"CategoryOrder";
	}
	else {
		sortKey = @"CustomerCategoryOrder";
	}
	
	
	
	[request setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:sortKey ascending:YES]]];
	
	
	NSError *error;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects != nil && objects.count > 0) {
		return objects;
	}
	else {
		if (error != nil) {
			NSLog(@"error:%@",[error description]);
		}			
	}
	return nil;
}
+(NSArray*) getBrandList
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Brand" inManagedObjectContext:context];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:entity];
	//NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ParentCategory == %@",[NSNull null]];
	//[request setPredicate:predicate];
	
	[request setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"BrandName" ascending:YES]]];
	
	NSError *error;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects != nil && objects.count > 0) {
		return objects;
	}
	else {
		if (error != nil) {
			NSLog(@"error:%@",[error description]);
		}			
	}
	return nil;
}

+(NSArray*) getBaseProductImages:(BaseProduct*)baseProduct
{
	NSArray *baseProductImages = [baseProduct.BaseProductImages allObjects];
	NSSortDescriptor *sortDescriptor;
	sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"ImageOrder"
												  ascending:YES] autorelease];
	NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
	
	return [baseProductImages sortedArrayUsingDescriptors:sortDescriptors];
}

+(NSArray*) getSearchShopList
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Shop" inManagedObjectContext:context];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:entity];
	
	NSError *error;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects != nil && objects.count > 0) {
		NSMutableArray *rs = [[[NSMutableArray alloc] init] autorelease];
		[rs addObject:[NSArray arrayWithObjects:@"All", @"-1",nil]];
		for (Shop *shop in objects) {
			[rs addObject:[NSArray arrayWithObjects:shop.ShopName, shop.ShopID,nil]];
		}
		return rs;
	}
	else {
		if (error != nil) {
			NSLog(@"error:%@",[error description]);
		}			
	}
	return nil;
}

+(NSArray*) getSearchMainCategory
{
	NSArray *obj = [CoreDataUtils getMainCategory];
	if (obj != nil && obj.count > 0) {
		NSMutableArray *rs = [[[NSMutableArray alloc] init] autorelease];
		[rs addObject:[NSArray arrayWithObjects:@"All", @"-1",nil]];
		for (Category *category in obj) {
			[rs addObject:[NSArray arrayWithObjects:category.CategoryName, category.CategoryID,nil]];
		}
		return rs;
	}
	return obj;
}

+(NSArray*) getSearchSubCategory:(NSString*)parentID
{
	if ([parentID isEqualToString:@"-1"]) {
		return [NSArray arrayWithObject:[NSArray arrayWithObjects:@"All",@"-1",nil]];
	}
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Category" inManagedObjectContext:context];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:entity];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ParentCategory.CategoryID == %@",parentID];
	[request setPredicate:predicate];
	NSError *error;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects != nil && objects.count > 0) {
		NSMutableArray *rs = [[[NSMutableArray alloc] init] autorelease];
		[rs addObject:[NSArray arrayWithObjects:@"All", @"-1",nil]];
		for (Category *category in objects) {
			[rs addObject:[NSArray arrayWithObjects:category.CategoryName, category.CategoryID,nil]];
		}
		return rs;
	}
	else {
		if (error != nil) {
			NSLog(@"error:%@",[error description]);
		}			
	}
	return nil;
}

+(NSArray*) getSearchBrands
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"Brand" inManagedObjectContext:context];
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	[request setEntity:entity];
	
	NSError *error;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects != nil && objects.count > 0) {
		NSMutableArray *rs = [[[NSMutableArray alloc] init] autorelease];
		[rs addObject:[NSArray arrayWithObjects:@"All", @"-1",nil]];
		for (Brand *brand in objects) {
			[rs addObject:[NSArray arrayWithObjects:brand.BrandName, brand.BrandID,nil]];
		}
		return rs;
	}
	else {
		if (error != nil) {
			NSLog(@"error:%@",[error description]);
		}			
	}
	return nil;
}

+(NSArray*) getSearchPriceType
{
	NSMutableArray *rs = [[[NSMutableArray alloc] init] autorelease];
	[rs addObject:[NSArray arrayWithObjects:@"All",@"-1",nil]]; 
	[rs addObject:[NSArray arrayWithObjects:@"Under",@"0",nil]]; 
	[rs addObject:[NSArray arrayWithObjects:@"Upper",@"1",@"Upper",nil]]; 
	[rs addObject:[NSArray arrayWithObjects:@"Between",@"2",@"Between",nil]]; 
	return rs;
}

+(BOOL) checkExistWishlistProduct:(BaseProduct*)baseProduct
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"WishList" inManagedObjectContext:context];
	NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
	[request setEntity:entity];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"BaseProduct == %@",baseProduct];
	[request setPredicate:predicate];
	
	NSError *error = nil;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects != nil && objects.count > 0) {
		return YES;
	}
	else {
		if (error != nil) {
			NSLog(@"error:%@",[error userInfo]);
		}			
	}
	return NO;
}

+(void) deleteAllWishlist
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	NSEntityDescription *entity = [NSEntityDescription  entityForName:@"WishList" inManagedObjectContext:context];
	NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
	[request setEntity:entity];
	
	NSError *error = nil;
	NSArray *objects = [context executeFetchRequest:request error:&error];
	if (objects != nil && objects.count > 0) {
		for (NSManagedObject * object in objects) {
			[context deleteObject:object];
		}
		NSError *saveError = nil;
		[context save:&saveError];
		
	}
	else {
		if (error != nil) {
			NSLog(@"error:%@",[error userInfo]);
		}			
	}
}

+(void) addWishList:(NSString*)baseProductID
{
	NSManagedObjectContext *context = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
	
	NSDictionary *condition= [[NSMutableDictionary alloc] init];
	[condition setValue:baseProductID forKey:@"BaseProductID"];
	BaseProduct *bpObj = (BaseProduct*)[CoreDataUtils getObjectEntity:@"BaseProduct" fromCondition:condition];
	if (bpObj) {
		WishList *object = [NSEntityDescription insertNewObjectForEntityForName:@"WishList" inManagedObjectContext:context];
		object.BaseProduct = bpObj;
	}
	[(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] saveContext];
}
@end
